// id="app" id='app' id=app
const attribute =
  /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/
const ncname = `[a-zA-Z_][\\-\\.0-9_a-zA-Z]*`
// 标签名 <my-heqader></my-header>
const qnameCapture = `((?:${ncname}\\:)?${ncname})`
//<div
const startTagOpen = new RegExp(`^<${qnameCapture}`)
// > />
const startTagClose = /^\s*(\/?)>/
//</div>
const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`)
function parseHtmlToAst(html) {
  let text,
    root,
    currentParent,
    stack = []
  console.log(html)
  while (html) {
    let textEnd = html.indexOf('<')
    if (textEnd === 0) {
      const startTagMatch = parseStartTag()
      if (startTagMatch) {
        start(startTagMatch.tagName, startTagMatch.attrs)
        continue
      }
      const endTagMatch = html.match(endTag)

      if (endTagMatch) {
        console.log({
          endTagMatch
        })
        advance(endTagMatch[0].length)
        end(endTagMatch[1])
        continue
      }
      console.log({
        startTagMatch
      })
    }

    if (textEnd > 0) {
      // console.log({
      //   textEnd
      // })
      text = html.substring(0, textEnd)
    }
    if (text) {
      advance(text.length)
      chars(text)
    }

  }

  function parseStartTag() {
    const start = html.match(startTagOpen)
    let end, attr
    if (start) {
      const match = {
        tagName: start[1],
        attrs: []
      }
      advance(start[0].length)

      while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
        // console.log({ attr })
        match.attrs.push({
          name: attr[1],
          value: attr[3] || attr[4] || attr[5]
        })
        advance(attr[0].length)
        // return match
      }

      if (end) {
        advance(end[0].length)
        return match
      }
    }
    console.log(start)
  }

  function advance(n) {
    html = html.substring(n)
  }

  //stack [div, span]
  function start(tagName, attrs) {
    const element = createASTElement(tagName, attrs)
    if (!root) {
      root = element
    }
    currentParent = element
    stack.push(element)
    console.log('------开始------')
    console.log(element)
  }

  function end(tagName) {
    const element = stack.pop()
    currentParent = stack[stack.length - 1]
    if (currentParent) {
      element.parent = currentParent
      currentParent.children.push(element)
    }
    console.log('-----结束------')
    console.log({
      tagName,
    })
  }

  function chars(text) {
    text = text.trim()
    console.log({
      text
    })
    if (text.length > 0) {
      currentParent.children.push({
        type: 3,
        text
      })
    }
    // console.log('------文本------')
    // console.log({
    //   text
    // })
  }

  function createASTElement(tagName, attrs) {
    return {
      tag: tagName,
      type: 1,
      children: [],
      attrs,
      parent
    }
  }
  return root
}

export {
  parseHtmlToAst
}
